package com.platform.module.user.controller;

import com.platform.module.common.base.*;
import com.platform.module.common.utils.AssertUtils;
import com.platform.module.pojo.user.dto.LoginDto;
import com.platform.module.pojo.user.dto.RegisterDto;
import com.platform.module.pojo.user.vo.LoginVo;
import com.platform.module.user.service.UserTokenService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.regex.Pattern;

@Slf4j
@RestController
@Tag(
        name = "移动端用户接口",
        description = "移动端用户接口"
)
@RequestMapping("/data/user/")
@AllArgsConstructor
public class UserController {

    static Pattern compile = Pattern.compile("^1\\d{10}$");
    private final UserTokenService userTokenService;

    @PostMapping("/login.v1")
    @NoNeedLogin
    @Operation(summary = "用户端登录接口", description = "用户端登录接口")
    public CommonResp<LoginVo> login(@Parameter(hidden = true) BaseReq req,
                                     @Valid @RequestBody LoginDto loginDto) {
        log.info("用户登录  appId：{} phone: {} password: {}", req.getAppId(), loginDto.getPhone(), loginDto.getPassword());
        AssertUtils.assertTrue(compile.matcher(loginDto.getPhone()).matches(), CodeEnum.手机号格式错误);
        return CommonResp.ok(userTokenService.phoneLogin(loginDto.getPhone(), loginDto.getPassword()));
    }

    @PostMapping("/register.v1")
    @NoNeedLogin
    @Operation(summary = "用户端注册接口", description = "用户端注册接口")
    public CommonResp<Void> register(@Parameter(hidden = true) BaseReq req,
                                     @Valid @RequestBody RegisterDto registerDto) {
        log.info("用户注册  appId：{} phone: {} password: {}", req.getAppId(), registerDto.getPhone(), registerDto.getPassword());
        AssertUtils.assertTrue(compile.matcher(registerDto.getPhone()).matches(), CodeEnum.手机号格式错误);
        return userTokenService.phoneRegisterDto(registerDto)?CommonResp.ok():CommonResp.fail(CodeEnum.FAILED);
    }
}
